package com.mugui.spring.net.authority;

import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.mugui.spring.base.Filter;
import com.mugui.spring.net.bean.Message;
import com.mugui.spring.net.bean.NetBag;
import com.mugui.spring.net.filter.FilterModel;

@Filter(weight = 97, value = { "*" }, type = Filter.POSITIVE)
@Component
public class AuthorityFilter implements FilterModel {

	private ReferenceConfig<GenericService> referenceConfig = null;

	public void init() {
		if (manager == null) {
			synchronized (AuthorityFilter.class) {
				if (manager == null) {
					if (referenceConfig == null) {
						referenceConfig = new ReferenceConfig<>();
						referenceConfig.setInterface(AuthorityServiceManagerApi.class);
						referenceConfig.setVersion("");
						referenceConfig.setGeneric(true);
					}
					GenericService genericService = referenceConfig.get();
					manager = genericService;
				}
			}
		}
	}

	@Value("${mugui.spring.authority.open:false}")
	private boolean isOpen;

	@Override
	public NetBag filter(NetBag bag) {
		if (!isOpen) {
			return bag;
		}
		try {
			init();
			if (manager != null) {
				Object $invoke = manager.$invoke("filter", new String[] { bag.getClass().getName() },
						new Object[] { bag });
				if ($invoke == null) {
					bag.setData(Message.error("权限错误"));
				} else if ($invoke instanceof Message) {
					bag.setData($invoke);
					return null;
				} else if ($invoke instanceof NetBag) {
					return (NetBag) $invoke;
				} else
					throw new RuntimeException("返回值错误" + $invoke);
			}
			bag.setData(Message.error("权限模块加载错误"));
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			bag.setData(Message.error("权限模块错误"));
			return null;
		}
	}

	private GenericService manager = null;

}
